<template>
  <div class="report-form-content">
    <el-form class="my-form"
             ref="objForm"
             :model="obj"
             :rules="rules"
             label-position="right"
             label-width="auto"
             label-suffix="："
             :disabled="oper === 'view' || oper === 'supplement'">
      <div class="tabs-form-head">
        <span>合同中止</span>
        <div class="">
          <el-button type="primary" plain @click="returnBtn">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认中止</el-button>
        </div>
      </div>
      <el-divider border-style="dashed" />
      <el-row :gutter="20">
        <el-col :sm="24" :lg="24" style="padding-left: 20px">
          <el-card class="update-log">
            <div class="report-form-list-content">
              <el-form-item label="中止经办人" prop="interruptUserId">
                <User v-model="obj.interruptUserId" keyName="id" keyShow="name" placeholder="中止经办人" title="用户查询" />
              </el-form-item>
              <el-form-item label="中止经办部门" prop="interruptDepartmentId">
                <Organization v-model="obj.interruptDepartmentId" keyName="id" keyShow="organizationName" placeholder="中止经办部门" title="组织架构查询" />
              </el-form-item>
            </div>
            <div class="report-form-list-content-1">
              <el-form-item label="中止原因" prop="interruptReason">
                <el-input v-model="obj.interruptReason" :autosize="{ minRows: 2, maxRows: 5}" type="textarea" class="textarea-1" />
              </el-form-item>
            </div>
            <el-row :gutter="20">
              <el-col :sm="24" :lg="24" style="padding-left: 20px">
                <el-card class="update-log" shadow="never">
                  <div class="file-list-btn">
                    <span class="file-list-btn-span">*温馨提示:保存成功后才能预览word文档和Excel报表</span>
                    <div class="file-list-btns">
                      <el-button type="primary" plain style="margin-right:1rem;" @click="selectAttachmentBtn"><svg-icon icon-class="search" />选择已上传的文件</el-button>
                      <FileUpload :isShowTip="false" v-model="oFiles" :isShowFileList="false" @uploadedSuccess="uploadedSuccessFn" />
                    </div>
                  </div>
                  <el-table :data="oFiles"
                            style="width: 100%; margin-top: 20px"
                            row-key="id"
                            border
                            default-expand-all
                            @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="附件类型">
                      <template v-slot="{row}">
                        <el-form-item prop="fileType">
                          <el-select v-model="row.type" placeholder="请选择" clearable filterable>
                            <el-option v-for="item in contractFiletypeList" :key="item.id" :label="`${item.code} - ${item.name} ${item.state === '0' ? '【已禁用】' : ''}`" :value="item.id" :disabled="item.state === '0'" />
                          </el-select>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column prop="original" label="附件名称" />
                    <el-table-column align="center" label="操作" width="160px" fixed="right">
                      <template #default="scope">
                        <el-button type="primary" link @click="downloadFile1(scope.row)">下载</el-button>
                        <el-button type="primary" link @click="viewFile1(scope.row)">预览</el-button>
                        <el-button type="danger" link @click="removeFile1(scope)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog v-model="selectAttachmentVisible" title="选择文件" width="70%" top="2vh">
      <selectAttachmentMultiple :isVisible="selectAttachmentVisible" @selectAttachment="selectAttachmentFn" @close="selectAttachmentVisible = false"></selectAttachmentMultiple>
    </el-dialog>
    <el-dialog v-model="attachmentVisible" title="附件预览" width="70%" top="2vh">
      <attachmentPreview v-model:attachmentId="previewAttachmentId" />
      <div style="text-align:right;">
        <el-button type="danger" @click="attachmentVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <selectApprove v-model:itemsVisible="dialogApproveVisible" @close="dialogApproveVisible = false" :business="'3008'" :businessId="obj.id" @doSubmit="doSubmit" />
  </div>
</template>
<script setup>
import {ref, getCurrentInstance} from 'vue'
import {doGet, doPost, doDownload} from "@/config/http";
import {svc, getListPageSize, notifySuccess, alertErrorMsg} from "@/config/common";
import selectAttachmentMultiple from '@/views/components/base/selectAttachmentMultiple.vue'
import attachmentPreview from '@/views/components/base/attachmentPreview.vue'
import { useRoute } from 'vue-router'
import SvgIcon from "@/components/SvgIcon/index.vue";
import {getUserId} from "@/config/cookie";
import useUserStore from "@/store/modules/user";
import selectApprove from "@/views/components/base/selectApprove.vue";
import User from "@/views/components/base/selectUser.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import initListStore from '@/store/modules/initList'

const route = useRoute()

const { proxy: ctx } = getCurrentInstance();

let obj = ref({
  contractInitialId: route.query.id, // 	合同ID
  createBy: '', // 创建人用户ID
  createTime: '',// 创建时间
  id: '', //  主键ID
  interruptDepartmentId: useUserStore().organization.id, // 中止经办人部门
  interruptReason: '', // 中止原因
  interruptUserId: getUserId(), // 中止经办人
  updateBy: '', // 最后修改时间
  version: '', // 数据版本
})
let objForm = ref(null)
let dialogApproveVisible = ref(false)
const oper = ref(route.query.oper)

let selectAttachmentVisible = ref(false)
let attachmentVisible = ref(false)
let previewAttachmentId = ref('')
let oFiles = ref([])

let contractTypeList = ref([]) // 合同类型
let contractCooperationList = ref([]) // 往来单位
let contractFeetypeList = ref([]) // 合同费用类型
let contractTemplateList = ref([]) // 合同模版
let bankList = ref([]) // 银行
let userList = ref([]) // 用户
let governmentList = ref([]) //  政府单位
let organizationList = ref([]) // 部门
let contractSignerList = ref([]) // 签订人
let contractFiletypeList = initListStore().contractFiletypeList // 合同附件类型

const rules = {}

// const initList = async () => {
//   let p1 = doGet(svc, '/contract-type/page', {pageSize: getListPageSize()}, false) // 合同类型
//   let p2 = doGet(svc, '/contract-cooperation/page', {pageSize: getListPageSize()}, false) // 往来单位
//   let p3 = doGet(svc, '/contract-feetype/page', {pageSize: getListPageSize()}, false) // 合同费用类型
//   let p4 = doGet(svc, '/contract-template/page', {pageSize: getListPageSize()}, false) // 合同模版
//   let p5 = doGet(svc, '/bank/page', {pageSize: getListPageSize()}, false) // 银行
//   let p6 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false) // 用户
//   let p7 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false) //  政府单位
//   let p8 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false) // 部门
//   let p9 = doGet(svc, '/contract-signer/page', {pageSize: getListPageSize()}, false) // 签订人
//   let p10 = doGet(svc, '/contract-filetype/page', {pageSize: getListPageSize()}, false) // 合同附件类型

//   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6, p7, p8, p9, p10])
//   contractTypeList.value = resArray[0]['records']
//   contractCooperationList.value = resArray[1]['records']
//   contractFeetypeList.value = resArray[2]['records']
//   contractTemplateList.value = resArray[3]['records']
//   bankList.value = resArray[4]['records']
//   userList.value = resArray[5]['records']
//   governmentList.value = resArray[6]['records']
//   organizationList.value = resArray[7]['records']
//   contractSignerList.value = resArray[8]['records']
//   contractFiletypeList.value = resArray[9]['records']
// }

// initList()

// 已上传文件
const selectAttachmentBtn = () => {
  selectAttachmentVisible.value = true
}

const selectAttachmentFn = (list) => {
  list.map(item => {
    uploadedSuccessFn(item)
  })
}

const uploadedSuccessFn = (file) => {
  console.log('file---------------',file)
  let filesObj = {
    attachmentId: file.attachmentId ? file.attachmentId : file.id, // 附件ID
    attachmentName: file.file ? file.file.name : file.fileName, // 附件名称
    attachmentType: '', // 附件类型
    attachmentUrl: file.url ? file.url : '',	//附件URL		false
    attachmentSize: file.size ? file.size : file.fileSize, //附件大小
    attachmentUpload: file.createTime, //附件上传时间
    attachmentUploader: file.updateBy, //附件上传人
    contractInitialInterruptId: '', // 初始合同中止ID
    createBy: '', // 创建人用户ID
    createTime: '', // 创建时间
    id: '', // 主键ID
    updateBy: '', // 最后修改人用户ID
    updateTime: '', // 最后修改时间
    version: '', // 数据版本
  }
  oFiles.value.push(filesObj)
}

const downloadFile1 = (row) => {
  console.log('row',row)
  if (row.attachmentId) {
    doDownload(svc, `/customAttachment/download/${row.attachmentId}`, {})
  } else {
    doDownload(svc, `/customAttachment/download/${row.id}`, {})
  }
}
const viewFile1 = (row) => {
  attachmentVisible.value = true
  setTimeout(() => {
    if (row.attachmentId) {
      previewAttachmentId.value = row.attachmentId
    } else {
      previewAttachmentId.value = row.id
    }
    console.debug('previewAttachmentId.value',previewAttachmentId.value)
  },100)
}
const removeFile1 = (scope) => {
  oFiles.value.splice(scope.$index, 1)
}

const handleSubmit = async () => {
  let v = await objForm.value.validate().catch((err)=>{return err})
  if (v !== true) {
    alertErrorMsg('表单验证不通过，请检查数据。')
    return
  }
  dialogApproveVisible.value = true
}

const doSubmit = async (data) => {
  let v = await objForm.value.validate().catch((err)=>{return err})
  if (v !== true) {
    alertErrorMsg('表单验证不通过，请检查数据。')
    return
  }
  obj.value.attachments = oFiles.value
  let o = {}
  o.oper = 'add'
  o.approveId = data.approveId
  o.approveNodes = data.approveNodes
  o.items = [obj.value]
  doPost(svc, `/customContractInitial/interruptContractInitial/${route.query.id}`, o, true).then(() => {
    notifySuccess('操作成功')
    returnBtn()
  })
}

const returnBtn = () => {
  switch (route.query.kind) {
    case '1':
      ctx.goTargetByName('contractInitial', {});
      break;
    case '2':
      ctx.goTargetByName('contractMain', {})
      break;
  }
}
</script>
<style scoped>
.report-form-content {
  padding: 20px;
}
.update-log {
  width: 100%;
  margin: 30px 0;
}
.report-list span:nth-child(1) {
  display: inline-block;
  width: 120px;
  text-align: right;
}
.tabs-form-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tabs-form-head span {
  font-size: 18px;
  color: #303133;
  font-weight: bold;
}
.file-list-btn {
  display: flex;
  align-items: center;
  justify-content: space-between
}
.file-list-btns {
  display: flex;
  align-items: center;
}
.file-list-btn-span {
  color: #F56C6C;
  font-size: 12px;
}
</style>
